package com.itheima.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * reggie-com.itheima.Controller
 * Administrator
 * 2023-03-08
 * 16:46
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

   @PostMapping
    public  R addCategory(@RequestBody Category category){
       boolean save = categoryService.save(category);
       if (save){
           return R.success("添加成功");
       }
       return R.error("添加失败");
   }

   @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize){
       Page<Category> categoryPage = new Page<>(page,pageSize);
       Page<Category> page1 = categoryService.page(categoryPage);
       if (page1!=null){
           return  R.success(categoryPage);
       }
       return  R.error("查询失败");
   }

   @DeleteMapping("")
    public R delete(@RequestParam ("id") Long id ){
       int i = categoryService.checkSortDish(id);
       if (i>0){
           return R.error("当前分类下有菜品，不能删除");
       }
       int i1 = categoryService.checkSortMeal(id);
       if (i1>0){
           return  R.error("当前分类下有套餐，不能删除");
       }

       boolean b = categoryService.removeById(id);
       if (b){
           return R.success("删除成功");
       }
       return R.error("删除失败");

   }

   @PutMapping
    public R updateSrot(@RequestBody Category category){
       boolean update = categoryService.updateById(category);
       if (update){
           return  R.success("修改成功");
       }
       return R.error("修改失败");
   }

    //查询所有的分类
   @GetMapping("/list")
    public R selectDishSort(Integer type){
       LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
       //select  * from  category where type=1  查询菜品分类列表
       //select * from category where type=2    查询套餐父类列表

       //select  * from category   客户端首页面,展示所有的菜品和套餐列表

       lqw.eq(type!=null,Category::getType,type); //where type=?
       List<Category> list = categoryService.list(lqw);
       if (list.size()!=0){
           return R.success(list);
       }
       return R.error("查询失败");
   }



}
